package ac.svn.accesscontrol.ui.helper;

import java.util.HashSet;
import java.util.Set;

import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import ac.svn.accesscontrol.manager.SVNInfoManager;
import ac.svn.accesscontrol.store.ISVNItem;
import ac.svn.accesscontrol.ui.GroupDeletionListener;
import ac.svn.accesscontrol.ui.UIComponentLibrary;
import ac.svn.accesscontrol.ui.panel.SVNItemPanel;

public class TextPaneLister 
{
    private Thread listingThread;
    private Set<ISVNItem> contents;
    private JPanel groupsPanel;
    private String strTextPaneId,strOwnerId;
    private String imageUrl;

    public TextPaneLister(String textPaneId,String ownerId)
    {
	this.strTextPaneId = textPaneId;
	this.strOwnerId = ownerId;
	listingThread = new Thread(new ListingTask());
	contents = new HashSet<ISVNItem>(0);
	groupsPanel = (JPanel) UIComponentLibrary.getComponent(textPaneId);
    }

    public class ListingTask implements Runnable{
	@Override
	public void run() 
	{
	    if(null != groupsPanel)
	    {
		contents = SVNInfoManager.getInfoManager().getUsersGroup(strOwnerId);
		groupsPanel.removeAll();
		for(ISVNItem item: contents)
		{
		    try{
			SVNItemPanel itemPanel = new SVNItemPanel(item.getName(), imageUrl);
			itemPanel.setStrMember(item.getId());
			itemPanel.setStrOwner(strOwnerId);
			itemPanel.getBtnDelete().addActionListener(new GroupDeletionListener(item.getId(), strOwnerId));
			groupsPanel.add(itemPanel);
		    }
		    catch(Exception e)
		    {

		    }
		}


		SwingUtilities.updateComponentTreeUI(groupsPanel);
	    }
	    else
	    {
		System.err.println("Text pane[ " +strTextPaneId+ "] not found!");
	    }
	}		
    }

    public synchronized void listContents()
    {
	if(listingThread.isAlive())
	{
	    listingThread.interrupt();
	}
	listingThread.run();			
    }

    public void setImageUrl(String imageUrl) 
    {
	this.imageUrl = imageUrl;
    }

    public void addItem(SVNItemPanel itemPanel) 
    {
	groupsPanel.add(itemPanel);
	SwingUtilities.updateComponentTreeUI(groupsPanel);
    }




}
